package com.nets.util;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * @author sig
 * @since 2016/9/17
 */
public class XmlParser {
    private Element element;

    public XmlParser(String pathname) {
        try {
            DocumentBuilderFactory factory =
                    DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new File(pathname));
            element = document.getDocumentElement();
        } catch (Exception e) {
            LogUtil.console.error(e.getMessage(), e);
        }
    }

    public String getString(String name) {
        NodeList list = element.getElementsByTagName(name);
        Node node = list.item(0);
        return node.getTextContent();
    }

    public byte getByte(String name) {
        return Byte.parseByte(getString(name));
    }

    public short getShort(String name) {
        return Short.parseShort(getString(name));
    }

    public int getInt(String name) {
        return Integer.parseInt(getString(name));
    }

    public long getLong(String name) {
        return Long.parseLong(getString(name));
    }
}
